import axios from "axios";
import { message } from "ant-design-vue";
function getQueryString(name: string): number {
  const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
  const r = window.location.search.substr(1).match(reg);
  if (r != null) return Number(unescape(r[2]));
  return 0;
}
let baseURL = "http://123.56.85.24:5000/api/";
if (getQueryString("ip") == 1) {
  baseURL = "http://192.168.1.200/api/admin";
} else if (getQueryString("ip") == 2) {
  baseURL = "http://fq.lycent.cn/api";
} else {
  baseURL = "/api/admin";
}
const service = axios.create({
  baseURL,
  timeout: 5000 // request timeout
});
// 发起请求之前的拦截器
service.interceptors.request.use(
  config => {
    // 如果有token 就携带tokon
    const token = window.localStorage.getItem("accessToken");
    if (token||config.url==="/login") {
      config.params=Object.assign(config.params||{},{token:token})
    }else{
      message.error("缺少token")
    }
    return config;
  },
  error => {
    message.error(error)
    Promise.reject(error)
  }
);
// 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data;
    if (response.status !== 200) {
      message.error(res.message || "网络错误")
      return Promise.reject(new Error(res.message || "Error"));
    } else {
      if(res.err!==0){
        message.error(res.msg || "当前请求过多,请稍后再试")
        return Promise.reject(new Error(res.msg || "Error"));
      }else{
        return res;
      }
    }
  },
  error => {
    message.error("服务器错误")
    return Promise.reject(error);
  }
);
export default service;
